import { useState, useEffect, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useWebSocket } from "@/hooks/use-websocket";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { 
  BarChart3, 
  Activity, 
  Search, 
  Filter, 
  Download, 
  RefreshCw,
  AlertCircle,
  CheckCircle,
  Info,
  AlertTriangle
} from "lucide-react";
import { ProxyLog, SystemMetrics } from "@shared/schema";

export default function Monitoring() {
  const { lastMessage } = useWebSocket();
  const [logs, setLogs] = useState<ProxyLog[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedLevel, setSelectedLevel] = useState<string>("all");
  const [selectedRule, setSelectedRule] = useState<string>("all");
  const [metricsHistory, setMetricsHistory] = useState<SystemMetrics[]>([]);

  const { data: initialLogs = [], isLoading: logsLoading } = useQuery({
    queryKey: ["/api/proxy-logs", { limit: 500 }],
    queryFn: async () => {
      const response = await fetch("/api/proxy-logs?limit=500");
      return response.json();
    },
  });

  const { data: proxyRules = [] } = useQuery({
    queryKey: ["/api/proxy-rules"],
  });

  const { data: currentMetrics } = useQuery({
    queryKey: ["/api/system-metrics"],
    refetchInterval: 5000,
  });

  const { data: historyMetrics = [] } = useQuery({
    queryKey: ["/api/system-metrics/history", { limit: 50 }],
    queryFn: async () => {
      const response = await fetch("/api/system-metrics/history?limit=50");
      return response.json();
    },
    refetchInterval: 10000,
  });

  useEffect(() => {
    setLogs(initialLogs);
  }, [initialLogs]);

  useEffect(() => {
    setMetricsHistory(historyMetrics);
  }, [historyMetrics]);

  useEffect(() => {
    if (lastMessage) {
      if (lastMessage.type === 'NEW_LOG') {
        setLogs(prev => [lastMessage.data, ...prev].slice(0, 500));
      } else if (lastMessage.type === 'METRICS_UPDATE') {
        setMetricsHistory(prev => [...prev, lastMessage.data].slice(-50));
      }
    }
  }, [lastMessage]);

  const filteredLogs = useMemo(() => {
    return logs.filter(log => {
      const matchesSearch = !searchTerm || 
        log.message.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesLevel = selectedLevel === "all" || log.level === selectedLevel;
      const matchesRule = selectedRule === "all" || 
        log.proxyRuleId?.toString() === selectedRule;
      
      return matchesSearch && matchesLevel && matchesRule;
    });
  }, [logs, searchTerm, selectedLevel, selectedRule]);

  const getLogIcon = (level: string) => {
    switch (level) {
      case 'ERROR':
        return <AlertCircle className="w-4 h-4 text-red-500" />;
      case 'WARN':
        return <AlertTriangle className="w-4 h-4 text-yellow-500" />;
      case 'INFO':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'DEBUG':
        return <Info className="w-4 h-4 text-blue-500" />;
      default:
        return <Info className="w-4 h-4 text-gray-500" />;
    }
  };

  const getLogLevelBadge = (level: string) => {
    const colors = {
      INFO: "bg-green-100 text-green-800 hover:bg-green-100",
      DEBUG: "bg-blue-100 text-blue-800 hover:bg-blue-100", 
      WARN: "bg-yellow-100 text-yellow-800 hover:bg-yellow-100",
      ERROR: "bg-red-100 text-red-800 hover:bg-red-100",
    };
    
    return (
      <Badge className={colors[level as keyof typeof colors] || "bg-gray-100 text-gray-800 hover:bg-gray-100"}>
        {level}
      </Badge>
    );
  };

  const getProxyRuleName = (proxyRuleId: number | null) => {
    if (!proxyRuleId) return "系统";
    const rule = proxyRules.find((r: any) => r.id === proxyRuleId);
    return rule?.name || "未知规则";
  };

  const exportLogs = () => {
    const dataStr = JSON.stringify(filteredLogs, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const exportFileDefaultName = `proxy-logs-${new Date().toISOString().split('T')[0]}.json`;
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  };

  const clearFilters = () => {
    setSearchTerm("");
    setSelectedLevel("all");
    setSelectedRule("all");
  };

  return (
    <div className="flex-1 overflow-hidden">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-semibold text-slate-800">监控日志</h2>
            <p className="text-slate-600">实时监控系统状态和代理日志</p>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="outline" onClick={exportLogs}>
              <Download className="w-4 h-4 mr-2" />
              导出日志
            </Button>
            <div className="flex items-center space-x-2">
              <BarChart3 className="w-5 h-5 text-slate-500" />
              <span className="text-sm text-slate-600">
                {filteredLogs.length} 条日志
              </span>
            </div>
          </div>
        </div>
      </header>

      <div className="p-6 overflow-y-auto h-full space-y-6">
        {/* System Metrics Overview */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-sm font-medium">CPU使用率</p>
                  <p className="text-2xl font-bold text-slate-800 mt-1">
                    {currentMetrics?.cpuUsage || 0}%
                  </p>
                </div>
                <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Activity className="text-blue-600 w-5 h-5" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-sm font-medium">内存使用</p>
                  <p className="text-2xl font-bold text-slate-800 mt-1">
                    {currentMetrics?.memoryUsage || 0}%
                  </p>
                </div>
                <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                  <BarChart3 className="text-green-600 w-5 h-5" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-sm font-medium">活跃连接</p>
                  <p className="text-2xl font-bold text-slate-800 mt-1">
                    {currentMetrics?.activeConnections || 0}
                  </p>
                </div>
                <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Activity className="text-purple-600 w-5 h-5" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-sm font-medium">错误率</p>
                  <p className="text-2xl font-bold text-slate-800 mt-1">
                    {currentMetrics?.errorRate || "0%"}
                  </p>
                </div>
                <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
                  <AlertCircle className="text-red-600 w-5 h-5" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Metrics History Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg font-semibold text-slate-800">系统性能趋势</CardTitle>
            <p className="text-slate-600 text-sm">过去一段时间的系统性能指标</p>
          </CardHeader>
          <CardContent>
            {metricsHistory.length === 0 ? (
              <div className="text-center py-8">
                <BarChart3 className="w-12 h-12 text-slate-300 mx-auto mb-4" />
                <p className="text-slate-500">暂无历史数据</p>
              </div>
            ) : (
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="text-center">
                    <p className="text-sm text-slate-600 mb-2">平均CPU使用率</p>
                    <p className="text-xl font-semibold text-slate-800">
                      {Math.round(
                        metricsHistory.reduce((sum, m) => sum + m.cpuUsage, 0) / metricsHistory.length
                      )}%
                    </p>
                  </div>
                  <div className="text-center">
                    <p className="text-sm text-slate-600 mb-2">平均内存使用率</p>
                    <p className="text-xl font-semibold text-slate-800">
                      {Math.round(
                        metricsHistory.reduce((sum, m) => sum + m.memoryUsage, 0) / metricsHistory.length
                      )}%
                    </p>
                  </div>
                  <div className="text-center">
                    <p className="text-sm text-slate-600 mb-2">平均响应时间</p>
                    <p className="text-xl font-semibold text-slate-800">
                      {Math.round(
                        metricsHistory.reduce((sum, m) => sum + m.avgResponseTime, 0) / metricsHistory.length
                      )}ms
                    </p>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Log Filters */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg font-semibold text-slate-800">日志过滤</CardTitle>
              <Button variant="outline" size="sm" onClick={clearFilters}>
                <RefreshCw className="w-4 h-4 mr-2" />
                清除过滤
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="search">搜索日志</Label>
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
                  <Input
                    id="search"
                    placeholder="搜索日志内容..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="level">日志级别</Label>
                <Select value={selectedLevel} onValueChange={setSelectedLevel}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部级别</SelectItem>
                    <SelectItem value="ERROR">错误</SelectItem>
                    <SelectItem value="WARN">警告</SelectItem>
                    <SelectItem value="INFO">信息</SelectItem>
                    <SelectItem value="DEBUG">调试</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="rule">代理规则</Label>
                <Select value={selectedRule} onValueChange={setSelectedRule}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部规则</SelectItem>
                    {proxyRules.map((rule: any) => (
                      <SelectItem key={rule.id} value={rule.id.toString()}>
                        {rule.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Real-time Logs */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-lg font-semibold text-slate-800">实时日志</CardTitle>
                <p className="text-slate-600 text-sm">
                  显示 {filteredLogs.length} 条日志，共 {logs.length} 条
                </p>
              </div>
              <div className="flex items-center space-x-2">
                <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse-dot"></div>
                <span className="text-sm text-slate-600">实时更新</span>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-96">
              {logsLoading ? (
                <div className="flex items-center justify-center h-32">
                  <div className="text-slate-500">加载中...</div>
                </div>
              ) : filteredLogs.length === 0 ? (
                <div className="text-center py-8">
                  <Filter className="w-12 h-12 text-slate-300 mx-auto mb-4" />
                  <p className="text-slate-500">
                    {logs.length === 0 ? "暂无日志记录" : "没有符合条件的日志"}
                  </p>
                </div>
              ) : (
                <div className="space-y-3">
                  {filteredLogs.map((log, index) => (
                    <div key={`${log.id}-${index}`} className="flex items-start space-x-3 p-3 rounded-lg hover:bg-slate-50">
                      <div className="flex items-center space-x-2 min-w-0 flex-shrink-0">
                        <span className="text-slate-400 text-xs">
                          {new Date(log.timestamp).toLocaleTimeString('zh-CN')}
                        </span>
                        {getLogIcon(log.level)}
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center space-x-2 mb-1">
                          {getLogLevelBadge(log.level)}
                          <span className="text-sm text-slate-600">
                            {getProxyRuleName(log.proxyRuleId)}
                          </span>
                        </div>
                        <p className="text-sm text-slate-800 break-words">{log.message}</p>
                        {log.metadata && (
                          <details className="mt-2">
                            <summary className="text-xs text-slate-500 cursor-pointer hover:text-slate-700">
                              详细信息
                            </summary>
                            <pre className="text-xs text-slate-600 mt-1 bg-slate-100 p-2 rounded overflow-x-auto">
                              {JSON.stringify(log.metadata, null, 2)}
                            </pre>
                          </details>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </ScrollArea>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
